import { useEnvStore } from '@/store/env'
import { getEcharts } from '../useEcharts'

const envStore = useEnvStore()

export type LineDataType = { symbol: string; value: number[] }
export type DataBarType = { itemStyle: { opacity: number }; value: number[] }
export type DataVType = { value: number[]; label?: any }

let myChart: echarts.ECharts | null = null
let symbolSize = 20

const symbolOffset = envStore.systemInfo.platform == 'ios' ? [0, '-5'] : [0, '-5']
const V_LINE_ICON = `path://
M39,0C17.5,0,0,17.5,0,39s17.5,39,39,39s39-17.5,39-39S60.5,0,39,0z M59,53.9c0,1.2-1,2.2-2.2,2.2H21.2
	c-1.2,0-2.2-1-2.2-2.2v-0.5c0-1.2,1-2.2,2.2-2.2h35.5c1.2,0,2.2,1,2.2,2.2V53.9z M59,39.2c0,1.2-1,2.2-2.2,2.2H21.2
	c-1.2,0-2.2-1-2.2-2.2v-0.5c0-1.2,1-2.2,2.2-2.2h35.5c1.2,0,2.2,1,2.2,2.2V39.2z M59,24.6c0,1.2-1,2.2-2.2,2.2H21.2
	c-1.2,0-2.2-1-2.2-2.2v-0.5c0-1.2,1-2.2,2.2-2.2h35.5c1.2,0,2.2,1,2.2,2.2V24.6z`
const H_LINE_ICON = `path://M39,0C17.5,0,0,17.5,0,39s17.5,39,39,39s39-17.5,39-39S60.5,0,39,0z M65.4,41.1L53.8,52.9c-1.1,1.1-2.8,1-3.9,0
c-1.1-1-1.1-2.8,0-3.9l7.4-7.5H20.6l7.3,7.5c1.1,1,1.1,2.8,0,3.9c-1.1,1.1-2.8,1.1-3.9,0L12.4,41.1c-0.6-0.6-0.8-1.3-0.8-2.1
s0.3-1.5,0.8-2.1L24,25.1c1-1.1,2.8-1.1,3.8,0c1.1,1,1.1,2.8,0,3.9l-7.3,7.5h36.7L49.9,29c-1.1-1-1.1-2.8,0-3.9
c1.1-1.1,2.8-1.1,3.9,0l11.6,11.8c0.6,0.6,0.8,1.3,0.8,2.1S66,40.5,65.4,41.1z`
// 折线图拐点图片y方向偏移量，对应的拖拽滑块也要偏移该长度
const offSetLine = 1.0

type RefValue<T> = Ref<T> | ComputedRef<T>
export function useRoomDayData(options: { tempLineData: RefValue<[number, number][]>; dataV: RefValue<DataVType[]> }) {
  const { tempLineData, dataV } = options
  const lineData = ref<LineDataType[]>([])
  const dataBar = ref<DataBarType[]>([]) // 柱状图坐标

  const echarts = getEcharts()

  function setChartInstance(chartInstance: echarts.ECharts) {
    myChart = chartInstance
  }
  function destroyChart() {
    if (myChart != null) {
      myChart.clear() //清空当前实例，会移除实例中所有的组件和图表
      myChart.dispose() //销毁实例，实例销毁后无法再被使用
      myChart = null
    }
  }

  // 给折线图增加起始点和结束点
  function initData() {
    lineData.value = []
    dataBar.value = []
    let interval = tempLineData.value[0][0] + 24 - tempLineData.value[tempLineData.value.length - 1][0]
    tempLineData.value.unshift([tempLineData.value[0][0] - interval, tempLineData.value[3][1]])
    tempLineData.value.push([tempLineData.value[4][0] + interval, tempLineData.value[1][1]])
    let dataTmp = []
    for (let i = 0; i < tempLineData.value.length; i++) {
      let obj = {
        symbol: '',
        value: [0, 0],
      }
      obj.value = tempLineData.value[i]
      if (i == 0 || i == 5) {
        obj.symbol = 'none'
      } else {
        obj.symbol = V_LINE_ICON
      }
      dataTmp.push(obj)
    }
    lineData.value = dataTmp

    // 新增柱状图
    dataTmp.forEach((item) => {
      dataBar.value.push({
        value: item.value,
        itemStyle: {
          opacity: item.symbol === 'none' ? 0 : 0.2,
        },
      })
    })
    console.log('initdata', dataBar.value)
    console.log('lineData', lineData.value)
  }

  // 调整起始点和结束点
  function adjustData() {
    let interval = lineData.value[1].value[0] + 24 - lineData.value[4].value[0]
    lineData.value[0].value = [lineData.value[1].value[0] - interval, lineData.value[4].value[1]]
    lineData.value[5].value = [lineData.value[4].value[0] + interval, lineData.value[1].value[1]]
  }

  function setOption() {
    const option = {
      xAxis: {
        min: 0,
        max: 24,
        type: 'value',
        boundaryGap: false,
        axisLine: {
          onZero: true,
          lineStyle: {
            color: '#65758A',
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          show: false,
        },
        minorTick: {
          show: false,
        },
        minorSplitLine: {
          show: false,
        },
        splitLine: {
          show: false,
        },
      },
      yAxis: {
        min: 5, // mos要求编程调节范围为5-35
        max: 35,
        type: 'value',
        axisLine: {
          onZero: true,
          lineStyle: {
            color: '#65758A',
          },
        },
        axisTick: {
          inside: true,
        },
        splitLine: {
          show: false,
        },
      },
      grid: {
        top: 30,
        bottom: 50,
        right: 20,
      },
      series: [
        {
          id: 'a',
          type: 'line',
          step: 'end',
          smooth: false,
          symbol: V_LINE_ICON,
          symbolKeepAspect: true,
          symbolOffset: [0, '50%'],
          legendHoverLink: false,
          label: {
            show: true,
            position: 'top',
            fontSize: 16,
            color: '#2D3746',
            formatter: (item: { value: string[] }) => {
              return item.value[1] + '°C'
            },
          },
          symbolSize,
          data: lineData.value,
          animation: false,
          clip: true,
          areaStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(60, 160, 220,0.39)',
                },
                {
                  offset: 0.34,
                  color: 'rgba(60, 160, 220,0.25)',
                },
                {
                  offset: 1,
                  color: 'rgba(60, 160, 220,0.00)',
                },
              ]),
            },
          },
          itemStyle: {
            normal: {
              color: '#408DF2', // 改变折线点的颜色
            },
          },
          lineStyle: {
            color: '#408DF2', // 改变折线颜色
            width: 2,
          },
        },
        {
          id: 'b',
          type: 'scatter',
          symbol: H_LINE_ICON,
          symbolKeepAspect: true,
          symbolOffset: symbolOffset,
          label: {
            normal: {
              show: true,
              position: 'top',
              distance: 5,
              formatter: (item: { value: number[] }) => {
                return item.value[0].toFixed(0) + '点'
              },
              color: '#2D3746',
            },
          },
          symbolSize,
          data: dataV.value,
          clip: false,
          progressive: 0,
          animation: false,
          itemStyle: {
            normal: {
              color: '#4475D5', // 改变折线点的颜色
            },
          },
        },
        {
          id: 'c',
          type: 'bar',
          barWidth: 1,
          data: dataBar.value,
          animation: false,
          itemStyle: {
            color: '#408DF2',
          },
        },
      ],
    }
    myChart?.setOption(option)
    dragInit()
  }

  function dragInit() {
    setTimeout(function () {
      // Add shadow circles (which is not visible) to enable drag.

      let dataTmp = JSON.parse(JSON.stringify(lineData.value))

      // 折线图上画拖动点
      myChart?.setOption({
        graphic: echarts.util.map(dataTmp, function (item, dataIndex) {
          return {
            id: dataIndex,
            type: 'circle',
            position: myChart?.convertToPixel('grid', (item as LineDataType).value),
            shape: {
              cx: 0,
              cy: symbolSize / 2,
              r: symbolSize - 5, // 比真实图形大一些，容易拖拽
            },
            invisible: true,
            draggable: true,
            ondrag: echarts.util.curry(onPointDraggingY, dataIndex as number),
            ondragend: echarts.util.curry(onDragYEnd, dataIndex as number),
            z: 100,
          }
        }),
      })
      let bomY = myChart?.convertToPixel('grid', [0, 0])[1]

      // x轴下方画水平拖动点
      myChart?.setOption({
        graphic: echarts.util.map(dataTmp, function (item, dataIndex) {
          return {
            id: 'bomDrag' + dataIndex,
            type: 'circle',
            position: [myChart?.convertToPixel('grid', (item as LineDataType).value)[0], bomY],
            shape: {
              cx: 0,
              cy: 0,
              r: symbolSize - 5, // 比真实图形大一些，容易拖拽
            },
            invisible: true,
            draggable: true,
            ondrag: echarts.util.curry(onPointDraggingX, dataIndex as number),
            ondragend: echarts.util.curry(onDragXEnd, dataIndex as number),
            z: 100,
          }
        }),
      })
    }, 0)
  }

  type CurryCallback = (
    this: {
      position: number[]
    },
    dataIndex: number
  ) => any

  /**
   * 竖直方向拖动，更改折线图上点y坐标
   *
   */
  let isMoveIn = false // 是否在拖动中。
  let lodingTime = 60 // 固定60毫秒的间隔。
  const onPointDraggingY: CurryCallback = function (dataIndex: number) {
    if (!myChart || dataIndex == 0 || dataIndex == 5) {
      return
    }
    if (isMoveIn) {
      return false
    }
    isMoveIn = true // 开始执行

    let currPositionY = myChart.convertFromPixel('grid', this.position)[1]
    currPositionY = Math.round(currPositionY * 2) / 2
    if (currPositionY > 35 - offSetLine) {
      lineData.value[dataIndex].value[1] = 35
    } else if (currPositionY < 5 - offSetLine) {
      lineData.value[dataIndex].value[1] = 5 // mos要求编程调节范围为5-35
    } else {
      lineData.value[dataIndex].value[1] = currPositionY + offSetLine
    }

    dataBar.value[dataIndex].value = lineData.value[dataIndex].value // 赋值柱状图
    dataBar.value[dataIndex].itemStyle = {
      opacity: 1,
    } // 拖拽时取消透明
    if (dataIndex == 1 || dataIndex == 4) {
      adjustData()
    }

    // // Update data
    myChart?.setOption({
      series: [
        {
          id: 'a',
          data: lineData.value,
        },
        {
          id: 'c',
          data: dataBar.value,
        },
      ],
    })
    setTimeout(() => {
      isMoveIn = false
    }, lodingTime) // 加60ms的间隔
  }
  /**
   * 水平方向拖动，同时修改水平拖动点y坐标保持固定
   *
   */
  const onPointDraggingX: CurryCallback = function (dataIndex: number) {
    if (!myChart || dataIndex == 0 || dataIndex == 5) {
      return
    }
    if (isMoveIn) {
      return false
    }
    isMoveIn = true // 开始拖拽

    let x = 0
    let currPositionX = myChart.convertFromPixel('grid', this.position)[0] // 当前拖拽的X坐标
    currPositionX = Math.round(currPositionX) // 取整

    // dataindex =0和5在折线图看不见的部分，为了画出折线图增加
    if (dataIndex == 1) {
      // 第一个调整点，不得小于0，和最后一个调整点时间间距也必须小于2
      let min = lineData.value[4].value[0] + 2 - 24
      if (min <= 0) {
        min = 0
      }

      if (currPositionX <= min) {
        x = min
      } else if (currPositionX >= lineData.value[dataIndex + 1].value[0] - 2) {
        // 不得和右边的调整点间距小于2
        x = lineData.value[dataIndex + 1].value[0] - 2 > 0 ? lineData.value[dataIndex + 1].value[0] - 2 : 0
      } else {
        x = currPositionX
      }
    } else if (dataIndex == 4) {
      // 最后一个调整点，不得大于24，和第一个调整点时间间距也必须小于2
      let max = lineData.value[1].value[0] + 24 - 2
      if (max >= 24) {
        max = 24
      }
      if (currPositionX >= max) {
        x = max
      } else if (currPositionX <= lineData.value[dataIndex - 1].value[0] + 2) {
        x = lineData.value[dataIndex - 1].value[0] + 2 < 24 ? lineData.value[dataIndex - 1].value[0] + 2 : 24
      } else {
        x = currPositionX
      }
    } else {
      if (currPositionX >= lineData.value[dataIndex + 1].value[0] - 2) {
        x = lineData.value[dataIndex + 1].value[0] - 2 > 0 ? lineData.value[dataIndex + 1].value[0] - 2 : 0
      } else if (currPositionX <= lineData.value[dataIndex - 1].value[0]) {
        x = lineData.value[dataIndex - 1].value[0] + 2 < 24 ? lineData.value[dataIndex - 1].value[0] + 2 : 24
      } else {
        x = currPositionX
      }
    }

    lineData.value[dataIndex].value[0] = x // 折线图
    dataV.value[dataIndex].value[0] = x // 底部按钮图
    dataBar.value[dataIndex].value[0] = x // 柱状图
    dataBar.value[dataIndex].itemStyle = {
      opacity: 1,
    } // 拖拽时取消透明
    dataV.value[dataIndex].label = {
      fontSize: 16,
    } // 拖拽时 增加底部按钮字体大小
    if (dataIndex == 1 || dataIndex == 4) {
      adjustData()
    }

    // 修改折线图坐标
    myChart.setOption({
      series: [
        {
          id: 'b',
          data: dataV.value,
        },
        {
          id: 'a',
          data: lineData.value,
        },
        {
          id: 'c',
          data: dataBar.value,
        },
      ],
    })
    setTimeout(() => {
      isMoveIn = false
    }, lodingTime) // 加60ms的间隔
  }
  /**
   * 竖直方向拖动松开，更改拖动点x坐标和折线图上的点一样，增加吸附效果
   *
   */
  function onDragYEnd(dataIndex: number) {
    if (dataIndex == 0 || dataIndex == 5 || !lineData.value[dataIndex]) {
      return
    }
    dataBar.value[dataIndex].itemStyle = {
      opacity: 0.2,
    } // 拖拽结束，字体改回透明
    // // Update data
    myChart?.setOption({
      graphic: [
        {
          id: dataIndex,
          $action: 'merge',
          position: myChart.convertToPixel('grid', lineData.value[dataIndex].value),
        },
      ],
      series: [
        {
          id: 'c',
          data: dataBar,
        },
      ],
    })
  }
  /**
   * 水平方向拖动松开，更改折线上拖动点x坐标和折线图上的点一样
   * 更改底部拖动点y坐标和显示的散点一样
   *
   */
  function onDragXEnd(dataIndex: number) {
    if (dataIndex == 0 || dataIndex == 5 || !lineData.value[dataIndex] || !dataV.value[dataIndex]) {
      return
    }
    dataBar.value[dataIndex].itemStyle = {
      opacity: 0.2,
    } // 拖拽结束，字体改回透明
    dataV.value[dataIndex].label = {
      fontSize: 12,
    } // 拖拽结束，字体改回透明
    myChart?.setOption({
      graphic: [
        {
          id: dataIndex,
          $action: 'merge',
          position: myChart.convertToPixel('grid', lineData.value[dataIndex].value),
        },
        {
          id: 'bomDrag' + dataIndex,
          $action: 'merge',
          position: myChart.convertToPixel('grid', dataV.value[dataIndex].value),
        },
      ],
      series: [
        {
          id: 'b',
          data: dataV.value,
        },
        {
          id: 'c',
          data: dataBar.value,
        },
      ],
    })
  }

  return {
    setChartInstance,
    destroyChart,
    lineData,
    initData,
    setOption,
  }
}
